package cz.zcu.fav.rat.managed.bean;

import java.io.IOException;
import java.io.OutputStream;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpServletResponse;

import cz.zcu.fav.rat.ical.ICalUserGenerator;

@ManagedBean(name = "icaluserprinterbean")
@RequestScoped
public class ICalUserPrinterBean
{
	@ManagedProperty(value = "#{param.id}")
	Integer id;
	
	public void render(ComponentSystemEvent event) throws IOException
	{
		printICal();
	}
	
	private void printICal() throws IOException
	{
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		HttpServletResponse response = (HttpServletResponse) externalContext
				.getResponse();
		response.reset();
		response.setContentType("text/calendar");
		OutputStream browserStream;

		browserStream = response.getOutputStream();
		ICalUserGenerator gen = SpringBeanFactory.getInstance().getBean(
				ICalUserGenerator.class);
		gen.createICal(browserStream, id);
		browserStream.close();

		facesContext.responseComplete();
	}
	

	public void setId(Integer id)
	{
		this.id = id;
	}
}
